package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.entity.Result;
import com.qingcheng.pojo.seckill.SeckillStatus;
import com.qingcheng.service.seckill.SeckillOrderService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/seckill/order")
public class SeckillOrderController {
    @Reference
    private SeckillOrderService seckillOrderService;
    /****
     * URL:/seckill/order/add
     * 添加订单
     * 调用Service增加订单
     * 匿名访问：anonymousUser
     * @param time
     * @param id
     */
    @RequestMapping(value = "/add")
    public Result add(String time,Long id){
        try {
            //获取用户登录名
            String username =
                    SecurityContextHolder.getContext().getAuthentication().getName();
            //用户未登录
            if(username.equalsIgnoreCase("anonymousUser")){
                //403表示用户未登录
                return new Result(403,"未登录！");
            }
            //调用Service增加订单
            Boolean bo = seckillOrderService.add(id, time, username);
            if(bo){
                //抢单成功
                return new Result(0,"下单成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(2,e.getMessage());
        }
        return new Result(1,"下单失败！");
    }

    @RequestMapping(value = "/query")
    public Result queryStatus(){
        //获取用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        //判断用户是否登录
        if (username.equals("anonymousUser")){
            //用户未登录
            return new Result(403,"用户未登录，请先登录");
        }
        try {
            SeckillStatus seckillStatus = seckillOrderService.queryStatus(username);
            if (seckillStatus!=null){
                return new Result(seckillStatus.getStatus(),"抢单状态");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //0表示抢单失败
            return new Result(0,e.getMessage());
        }

        return new Result(404,"无相关信息");
    }
}

